const WebSocket = require("ws");

const wss = new WebSocket.Server({ port: 8080 });

wss.on("connection", (ws) => {
  console.log("客户端已连接");

  // 监听客户端消息
  ws.on("message", (message) => {
    console.log(`收到消息: ${message}`);

    // 回复消息给客户端
    ws.send(`服务器收到: ${message}`);
  });

  ws.on("close", () => {
    console.log("客户端断开连接");
  });

  ws.on("error", (error) => {
    console.error("WebSocket 错误:", error);
  });

  // 发送欢迎消息
  ws.send("欢迎连接 WebSocket 服务器");
});

console.log("WebSocket 服务器启动，监听端口 8080");
